import json
import logging
import os
from typing import Any, List

from fastapi import APIRouter, Depends, Body, HTTPException
from llama_index.core.tools import FunctionTool
from sqlalchemy import or_, func
from sqlalchemy.orm import Session, Query

from app.core.config import settings
from app.core.security import get_current_user
from app.db.session import get_db
from sks.tools import get_tools
from app.models import User
from app.models.ai import AIAgent, AIAgentSyncFlag, Tools
from app.models.base import BaseEnumYesNo, BaseEnumEnabledDisabled
from app.schemas.ai import AIAgentCreate, AIAgentUpdate, AIApiInit, LookupAiModelUseAiConfigQo, AIToolsListQo, \
    AIToolsUpdate
from app.schemas.base_so import AIAgentListQo, DetailParam, DelParam, LookupSksTableAiAgentUseAgentQO, BaseListQo, \
    LookupSksTableToolsUseAgentQO
from app.schemas.result import BaseResult, okResult, BaseListResult, BaseSksTableResult, sksTableResult
from app.services.ai_services import AIAgentGroupService, AIService
from app.models.ai import AIApiKey
from app.models.ai import AIModel
from app.schemas.ai import AIModelCreate, AIModelUpdate, AIModelListQo
from app.schemas.ai import AIApiCreate, AIApiUpdate, AIApiListQo

logger = logging.getLogger(__name__)
router = APIRouter()


@router.get("/ai-agent-group/list", response_model=BaseListResult)
def get_ai_agent_group_list(
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
) -> Any:
    data = AIAgentGroupService.get_ai_agent_group_list_format_dict(db)
    return okResult(data=data).json_encoders()



@router.post("/ai-agent/list", response_model=BaseListResult)
def get_ai_agent_list(
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
        qo: AIAgentListQo = Body()
) -> Any:
    page = qo.pageNum
    per_page = qo.pageSize
    offset = (page - 1) * per_page
    conditions = []
    if qo.searchValue:
        conditions.append(
            or_(AIAgent.system_prompt.like(f"%{qo.searchValue}%"), AIAgent.name.like(f"%{qo.searchValue}%"),
                AIAgent.description.like(f"%{qo.searchValue}%")))

    if qo.group:
        conditions.append(func.find_in_set(qo.group, AIAgent.group))


    total = db.query(func.count(AIAgent.id)).filter(*conditions).scalar()

    query: Query = (db.query(AIAgent,AIModel,AIApiKey)
                    .outerjoin(AIModel, AIAgent.ai_model_id == AIModel.id)
                    .outerjoin(AIApiKey, AIModel.ai_api_id == AIApiKey.id)
                    .filter(*conditions)
                    )

    _result = (
        query
        .order_by(AIAgent.id.desc())
        .limit(per_page)
        .offset(offset)
        .all()
    )
    list=[]
    for aiAgent,aiModel,aiApiKey in _result:
        _dict=aiAgent.to_dict_use_result()
        _dict['v_ai_model_info']=AIService.format_ai_model_view_info(aiModel, aiApiKey)
        _dict['v_agent_ids_info']=AIService.format_agent_ids_info(db,aiAgent.agent_ids)
        _dict['v_tools_info']=AIService.format_tools_info(db,aiAgent.tools)

        list.append(_dict)
    return BaseListResult(
        rows=list,
        total=total,
    ).json_encoders()


@router.post("/ai-agent/getDetail", response_model=BaseResult)
def get_ai_agent(
        *,
        db: Session = Depends(get_db),
        param: DetailParam = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Get ai-agent by ID.
    """

    kb = (
        db.query(AIAgent)
        .filter(
            AIAgent.id == param.id,
        )
        .first()
    )

    if not kb:
        raise HTTPException(status_code=500, detail="找不到智能体")


    return okResult(data=kb).json_encoders()


@router.post("/ai-agent/init", response_model=BaseResult)
def init_ai_agent(
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
):
    AGENTS_JSON = f'{settings.PROJECT_PATH}{os.sep}data{os.sep}agents.json'
    with open(AGENTS_JSON, "r", encoding="utf-8") as f:
        json_str = f.read()
        data = json.loads(json_str)  # 从字符串解析
        data.append({
            "id": 1999,
            "name": "️ 默认助手",
            "emoji": "😀",
            "description": "️ 默认助手",
            "group": ["默认"],
            "prompt": ""
        })
        for item in data:
            agent = db.query(AIAgent).filter(AIAgent.id == item['id']).first()
            if agent and agent.sync_flag == AIAgentSyncFlag.DISABLED.value.value:
                continue
            elif agent is None:
                agent = AIAgent(
                    id=item['id'],
                )
                for group in item['group']:
                    AIAgentGroupService.auto_create_ai_agent_group(db, user_id=current_user.id, groups=group)

            agent.name = item['name']
            agent.emoji = item['emoji']
            agent.description = item['description']
            agent.group = ','.join(item['group']) if item['group'] else ''
            agent.system_prompt = item['prompt']
            agent.sync_flag = AIAgentSyncFlag.ENABLED.value.value
            agent.user_id = current_user.id
            agent.status = BaseEnumEnabledDisabled.DISABLED.value.value
            db.add(agent)
        db.commit()

    return okResult()


@router.post("/ai-agent/add", response_model=BaseResult)
def create_ai_agent(
        *,
        db: Session = Depends(get_db),
        data_in: AIAgentCreate = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Create new AIAgent base.
    """
    data = AIAgent(
        name=data_in.name,
        description=data_in.description,
        emoji=data_in.emoji,
        group=data_in.group,
        system_prompt=data_in.system_prompt,
        summarize_prompt=data_in.summarize_prompt,
        tool_desc=data_in.tool_desc,
        tools=data_in.tools,
        kb_id=data_in.kb_id,
        agent_ids=data_in.agent_ids,
        sync_flag=AIAgentSyncFlag.ENABLED.value.value,
        ai_model_id=data_in.ai_model_id,
        user_id=current_user.id,
        status= data_in.status,
    )
    AIAgentGroupService.auto_create_ai_agent_group(db, user_id=current_user.id, groups=data_in.group)
    db.add(data)
    db.commit()
    # 刷新会话以获取新生成的主键
    db.flush()
    db.refresh(data)
    logger.info(f"AIAgent base created: {data.name} for user {current_user.id}")
    return okResult(data=data).json_encoders()


@router.post("/ai-agent/edit", response_model=BaseResult)
def edit_ai_agent(
        *,
        db: Session = Depends(get_db),
        data_in: AIAgentUpdate = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
     edit AIAgent .
    """
    data = db.query(AIAgent).filter(
        AIAgent.id == data_in.id,
    ).first()
    if not data:
        raise HTTPException(status_code=500, detail="智能体不存在或已被删除")
    data.name = data_in.name
    data.description = data_in.description
    data.emoji = data_in.emoji
    data.group = data_in.group
    data.system_prompt = data_in.system_prompt
    data.summarize_prompt = data_in.summarize_prompt
    data.tool_desc = data_in.tool_desc
    data.tools = data_in.tools
    data.kb_id = data_in.kb_id
    data.agent_ids = data_in.agent_ids
    data.sync_flag = AIAgentSyncFlag.DISABLED.value.value
    data.ai_model_id = data_in.ai_model_id
    data.status = data_in.status

    db.add(data)
    db.commit()
    # 刷新会话以获取新生成的主键
    db.flush()
    db.refresh(data)
    logger.info(f"AIAgent base updated: {data.name} for user {current_user.id}")
    return okResult(data=data).json_encoders()


@router.delete("/ai-agent/delete")
async def delete_ai_agent(
        *,
        db: Session = Depends(get_db),
        param: DelParam = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Delete AIAgent.
    """
    ids = param.ids

    query = (db.query(AIAgent)
    .filter(
        AIAgent.id.in_(ids),
    )
    )
    query.delete()
    db.commit()
    return okResult()


@router.post("/ai-api/list", response_model=BaseListResult)
def get_ai_api_list(
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
        qo: AIApiListQo = Body()
) -> Any:
    page = qo.pageNum
    per_page = qo.pageSize
    offset = (page - 1) * per_page
    conditions = []
    if qo.searchValue:
        conditions.append(
            or_(AIApiKey.name.like(f"%{qo.searchValue}%"), AIApiKey.description.like(f"%{qo.searchValue}%")))

    query: Query = (db.query(AIApiKey)
                    .filter(*conditions)
                    )

    total = query.count()

    rows = (
        query
        .order_by(AIApiKey.status.desc(),AIApiKey.id.desc())
        .limit(per_page)
        .offset(offset)
        .all()
    )
    return BaseListResult(
        rows=rows,
        total=total,
    ).json_encoders()


@router.post("/ai-api/add", response_model=BaseResult)
def create_ai_api(
        *,
        db: Session = Depends(get_db),
        data_in: AIApiCreate = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Create new AIApi.
    """
    data = AIApiKey(
        name=data_in.name,
        description=data_in.description,
        remark=data_in.remark,
        api_base=data_in.api_base,
        api_key=data_in.api_key,
        api_token=data_in.api_token,
        user_id=current_user.id,
    )
    db.add(data)
    db.commit()
    # 刷新会话以获取新生成的主键
    db.flush()
    db.refresh(data)
    logger.info(f"AIApi created: {data.name} for user {current_user.id}")
    return okResult(data=data).json_encoders()


@router.post("/ai-api/getDetail", response_model=BaseResult)
def get_ai_api_detail(
        *,
        db: Session = Depends(get_db),
        param: DetailParam = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Get ai-api by ID.
    """
    api = (
        db.query(AIApiKey)
        .filter(
            AIApiKey.id == param.id,
        )
        .first()
    )

    if not api:
        raise HTTPException(status_code=500, detail="找不到API")

    return okResult(data=api).json_encoders()


@router.post("/ai-api/edit", response_model=BaseResult)
def edit_ai_api(
        *,
        db: Session = Depends(get_db),
        data_in: AIApiUpdate = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Edit AIApi.
    """
    data = db.query(AIApiKey).filter(
        AIApiKey.id == data_in.id,
    ).first()
    if not data:
        raise HTTPException(status_code=500, detail="API不存在或已被删除")
    data.name = data_in.name
    data.description = data_in.description
    data.remark = data_in.remark
    data.api_base = data_in.api_base
    data.api_key = data_in.api_key
    data.api_token = data_in.api_token
    data.status = data_in.status
    data.is_system=data_in.is_system

    db.add(data)
    db.commit()
    # 刷新会话以获取新生成的主键
    db.flush()
    db.refresh(data)
    logger.info(f"AIApi updated: {data.name} for user {current_user.id}")
    return okResult(data=data).json_encoders()


@router.delete("/ai-api/delete")
async def delete_ai_api(
        *,
        db: Session = Depends(get_db),
        param: DelParam = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Delete AIApi.
    """
    ids = param.ids

    query = (
        db.query(AIApiKey)
        .filter(
            AIApiKey.id.in_(ids),
        )
    )
    query.delete()
    db.commit()
    return okResult()


@router.post("/ai-api/init", response_model=BaseResult)
def init_ai_api(
        *,
        db: Session = Depends(get_db),
        data_in: List[AIApiInit] = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    初始化数据来自前端,Cherry Studio开源项目
    """

    _count = db.query(AIApiKey).count()
    if _count > 0:
        raise HTTPException(status_code=500, detail="API 已经初始化过,请勿重复初始化")

    for item in data_in:
        data = AIApiKey(
            id=item.id,
            name=item.name,
            type=item.type,
            description=item.description,
            api_base=item.api_base,
            api_key=item.api_key,
            api_token=item.api_token,
            user_id=current_user.id,
            is_system=BaseEnumYesNo.YES.value.value,
            status=BaseEnumEnabledDisabled.DISABLED.value.value,

        )
        db.add(data)
        # 刷新会话以获取新生成的主键
        db.flush()
        db.refresh(data)
        models = [
            AIModel(
                ai_api_id=data.id,
                model_name=model.name,
                description=model.description,
                model_group=model.group,
                status=BaseEnumEnabledDisabled.DISABLED.value.value,
            ) for model in item.models
        ]
        db.add_all(models)
    db.commit()
    logger.info(f"AIApi init for user {current_user.id}")
    return okResult().json_encoders()


@router.post("/ai-model/list", response_model=BaseSksTableResult)
def get_ai_model_list(
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
        qo: AIModelListQo = Body()
) -> Any:
    page = qo.pageNum
    per_page = qo.pageSize
    offset = (page - 1) * per_page
    conditions = []
    conditions.append(AIModel.ai_api_id == qo.ai_api_id)
    if qo.searchValue:
        conditions.append(
            or_(AIModel.model.like(f"%{qo.searchValue}%"), AIModel.description.like(f"%{qo.searchValue}%")))

    query: Query = (db.query(AIModel)
                    .filter(*conditions)
                    )

    total = query.count()

    rows = (
        query
        .order_by(AIModel.id.desc())
        .limit(per_page)
        .offset(offset)
        .all()
    )
    result = BaseSksTableResult(
        list=rows,
        total=total,
    )
    return result.json_encoders()


@router.post("/ai-model/add", response_model=BaseResult)
def create_ai_model(
        *,
        db: Session = Depends(get_db),
        data_in: AIModelCreate = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Create new AIModel.
    """
    data = AIModel(
        ai_api_id=data_in.ai_api_id,
        model_name=data_in.model_name,
        model_group=data_in.model_group,
        description=data_in.description,
        type=data_in.type,
        has_tool=data_in.has_tool,
        status=data_in.status,
    )
    db.add(data)
    db.commit()
    # 刷新会话以获取新生成的主键
    db.flush()
    db.refresh(data)
    logger.info(f"AIModel created: {data.model_name} for user {current_user.id}")
    return okResult(data=data).json_encoders()


@router.post("/ai-model/getDetail", response_model=BaseResult)
def get_ai_model_detail(
        *,
        db: Session = Depends(get_db),
        param: DetailParam = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Get ai-model by ID.
    """
    model = (
        db.query(AIModel)
        .filter(
            AIModel.id == param.id,
        )
        .first()
    )

    if not model:
        raise HTTPException(status_code=500, detail="找不到模型")

    return okResult(data=model).json_encoders()


@router.post("/ai-model/edit", response_model=BaseResult)
def edit_ai_model(
        *,
        db: Session = Depends(get_db),
        data_in: AIModelUpdate = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Edit AIModel.
    """
    data = db.query(AIModel).filter(
        AIModel.id == data_in.id,
    ).first()
    if not data:
        raise HTTPException(status_code=500, detail="模型不存在或已被删除")
    data.ai_api_id = data_in.ai_api_id
    data.status = data_in.status
    data.model_name = data_in.model_name
    data.model_group = data_in.model_group
    data.description = data_in.description
    data.type = data_in.type
    data.has_tool = data_in.has_tool

    db.add(data)
    db.commit()
    # 刷新会话以获取新生成的主键
    db.flush()
    db.refresh(data)
    logger.info(f"AIModel updated: {data.model_name} for user {current_user.id}")
    return okResult(data=data).json_encoders()


@router.delete("/ai-model/delete")
async def delete_ai_model(
        *,
        db: Session = Depends(get_db),
        param: DelParam = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Delete AIModel.
    """
    ids = param.ids

    query = (
        db.query(AIModel)
        .filter(
            AIModel.id.in_(ids),
        )
    )
    query.delete()
    db.commit()
    return okResult()

@router.post("/ai-model/lookup-use-aiConfig", response_model=BaseSksTableResult)
def lookup_ai_model_use_ai_config(
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
        qo: LookupAiModelUseAiConfigQo = Body()
) -> Any:
    conditions = []
    conditions.append(AIModel.status == BaseEnumEnabledDisabled.ENABLED.value.value)

    query: Query = (db.query(AIModel,AIApiKey).join(AIApiKey, AIModel.ai_api_id == AIApiKey.id)
                    .filter(*conditions)
                    )

    # total = query.count()

    dbList = (
        query
        .order_by(AIModel.ai_api_id.desc(),AIModel.model_group.desc(),AIModel.id.desc())
        .all()
    )
    total= len(dbList)
    rows=[]
    for aiModel, aiApi in dbList:
        rows.append({
            "id": aiModel.id,
            "model_name": aiModel.model_name,
            "model_group": aiModel.model_group,
            "api_provider": aiApi.description,
        })
    result = BaseSksTableResult(
        list=rows,
        total=total,
    )
    return result.json_encoders()

@router.post("/ai-agent/lookup-use-chat", response_model=BaseSksTableResult)
def lookup_ai_agent_use_chat(
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
        qo: AIAgentListQo = Body()
) -> Any:
    conditions = []
    conditions.append(AIAgent.status == BaseEnumEnabledDisabled.ENABLED.value.value)

    # if qo.searchValue:
    #     conditions.append(
    #         or_(AIAgent.system_prompt.like(f"%{qo.searchValue}%"), AIAgent.name.like(f"%{qo.searchValue}%"),
    #             AIAgent.description.like(f"%{qo.searchValue}%")))
    # if qo.group:
    #     conditions.append(func.find_in_set(qo.group, AIAgent.group))

    query: Query = (db.query(AIAgent)
                    .filter(*conditions)
                    )


    rows = (
        query
        .order_by(AIAgent.id.desc())
        .all()
    )
    total= len(rows)
    list=[]
    for row in rows:
        _dict=row.to_dict_use_result()
        _agentInfo,aiAgent,aiModel,aiApi=AIService.get_ai_agent_view_info(db, row.id)
        _dict['v_ai_model_info']=_agentInfo
        list.append(_dict)
    return BaseSksTableResult(
        list=list,
        total=total,
    ).json_encoders()




@router.post("/ai-tools/list", response_model=BaseSksTableResult)
def get_ai_tools_list(
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
        qo: AIToolsListQo = Body()
) -> Any:
    page = qo.pageNum
    per_page = qo.pageSize
    offset = (page - 1) * per_page
    conditions = []
    if qo.searchValue:
        conditions.append(
            or_(Tools.tool_name.like(f"%{qo.searchValue}%"), Tools.tool_desc.like(f"%{qo.searchValue}%")))

    query: Query = (db.query(Tools)
                    .filter(*conditions)
                    )

    total = query.count()

    rows = (
        query
        .order_by(Tools.id.desc())
        .limit(per_page)
        .offset(offset)
        .all()
    )
    result = BaseSksTableResult(
        list=rows,
        total=total,
    )
    return result.json_encoders()

@router.post("/ai-tools/init", response_model=BaseResult)
def init_ai_tools(
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
):
    tools:list[FunctionTool]=get_tools(True)
    for item in tools:
        tool_name=item.metadata.name
        tool_desc=item.metadata.description
        ai_tool = db.query(Tools).filter(Tools.tool_name == tool_name).first()
        if ai_tool is None:
            ai_tool = Tools()
            ai_tool.status = BaseEnumEnabledDisabled.ENABLED.value.value
        ai_tool.tool_name=tool_name
        ai_tool.tool_desc=tool_desc
        db.add(ai_tool)

    db.commit()

    return okResult()

# @router.post("/ai-tools/add", response_model=BaseResult)
# def create_ai_tools(
#         *,
#         db: Session = Depends(get_db),
#         data_in: AIToolsCreate = Body(),
#         current_user: User = Depends(get_current_user)
# ) -> Any:
#     """
#     Create new Tools.
#     """
#     data = Tools(
#         ai_api_id=data_in.ai_api_id,
#         model_name=data_in.model_name,
#         model_group=data_in.model_group,
#         description=data_in.description,
#         status=data_in.status,
#     )
#     db.add(data)
#     db.commit()
#     # 刷新会话以获取新生成的主键
#     db.flush()
#     db.refresh(data)
#     logger.info(f"Tools created: {data.model_name} for user {current_user.id}")
#     return okResult(data=data).json_encoders()


@router.post("/ai-tools/getDetail", response_model=BaseResult)
def get_ai_tools_detail(
        *,
        db: Session = Depends(get_db),
        param: DetailParam = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Get ai-tools by ID.
    """
    item = (
        db.query(Tools)
        .filter(
            Tools.id == param.id,
            )
        .first()
    )

    if not item:
        raise HTTPException(status_code=500, detail="找不到模型")

    return okResult(data=item).json_encoders()


@router.post("/ai-tools/edit", response_model=BaseResult)
def edit_ai_tools(
        *,
        db: Session = Depends(get_db),
        data_in: AIToolsUpdate = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Edit Tools.
    """
    data = db.query(Tools).filter(
        Tools.id == data_in.id,
        ).first()
    if not data:
        raise HTTPException(status_code=500, detail="模型不存在或已被删除")
    data.remark = data_in.remark
    data.status = data_in.status

    db.add(data)
    db.commit()
    # 刷新会话以获取新生成的主键
    db.flush()
    db.refresh(data)
    logger.info(f"Tools updated: {data.tool_name} for user {current_user.id}")
    return okResult(data=data).json_encoders()


@router.delete("/ai-tools/delete")
async def delete_ai_tools(
        *,
        db: Session = Depends(get_db),
        param: DelParam = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Delete Tools.
    """
    ids = param.ids

    query = (
        db.query(Tools)
        .filter(
            Tools.id.in_(ids),
        )
    )
    query.delete()
    db.commit()
    return okResult()







@router.post("/ai-tools/lookup-sks-table-use-agent", response_model=BaseSksTableResult)
def lookup_sks_table_ai_tools_use_agent(
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
        qo: LookupSksTableToolsUseAgentQO = Body()
) -> Any:
    conditions = []
    conditions.append(Tools.status == BaseEnumEnabledDisabled.ENABLED.value.value)



    page = qo.pageNum
    per_page = qo.pageSize
    offset = (page - 1) * per_page
    conditions = []
    if qo.searchValue:
        conditions.append(
            or_(Tools.tool_name.like(f"%{qo.searchValue}%"), Tools.tool_desc.like(f"%{qo.searchValue}%")))

    query: Query = (db.query(Tools)
                    .filter(*conditions)
                    )

    total = query.count()

    list = (
        query
        .order_by(Tools.id.desc())
        .limit(per_page)
        .offset(offset)
        .all()
    )

    return sksTableResult(
        list=list,
        total=total,
    ).json_encoders()

@router.post("/ai-agent/lookup-sks-table-use-agent", response_model=BaseSksTableResult)
def lookup_sks_table_ai_agent_use_agent(
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
        qo: LookupSksTableAiAgentUseAgentQO = Body()
) -> Any:
    conditions = []
    conditions.append(AIAgent.status == BaseEnumEnabledDisabled.ENABLED.value.value)

    # if qo.searchValue:
    #     conditions.append(
    #         or_(AIAgent.system_prompt.like(f"%{qo.searchValue}%"), AIAgent.name.like(f"%{qo.searchValue}%"),
    #             AIAgent.description.like(f"%{qo.searchValue}%")))
    if qo.idNotIn_not_none():
        conditions.append(AIAgent.id.notin_(qo.idNotIn))

    query: Query = (db.query(AIAgent)
                    .filter(*conditions)
                    )


    rows = (
        query
        .order_by(AIAgent.id.desc())
        .all()
    )
    total= len(rows)
    list=[]
    for row in rows:
        _dict=row.to_dict_use_result()
        _agentInfo,aiAgent,aiModel,aiApi=AIService.get_ai_agent_view_info(db, row.id)
        _dict['v_ai_model_info']=_agentInfo
        list.append(_dict)
    return sksTableResult(
        list=list,
        total=total,
    ).json_encoders()

